import os, string, regsub, time
from chmod import chmod
import vcs
from vcs import TRUE, FALSE, NL, SYSTEM, WINDOWS, UNIX
from vcs import NULLDEV, DELIMITER
from vcs import is_readable, is_writable
from vcs import out, err
import sys

# Modules required for the Dialogs
from etgui import *
from etguiimpl import PotGuiPopupButton
from PageLayout import *

from tclog import TClog
import TCSettings
from TCSettings import BuildCmdOptions, readSettings, writeSettings, TEST

#TRUE if testing by TakeFive
#TF_TEST = TRUE

VERBOSE = TRUE

gTeamc="teamc"
gMod = "TeamConnection:"

gTCTmpDir = ''

# ---- log handling ----------------------------------

_last_rep_file = ""
_last_log = None

def log_with_history(use_cache=FALSE, debug=TEST):
	marker="log_with_history: "
	if debug > 0: 
		print "start", gMod+marker+NL,
	global _last_rep_file, _last_log
	if use_cache and (_last_rep_file == vcs.repositoryFile):
		# _last_log.reuse()
		if debug > 0: 
			print "end", gMod+marker+NL,
		return _last_log
	else:
		if string.find(vcs.repositoryFile, ' ') > 0:	# multiple files
			if debug > 0: 
				print "end", gMod+marker+NL,
			return TClog(vcs.workingFile)
		_last_rep_file = vcs.repositoryFile
		_last_log = TClog(vcs.workingFile, debug)
		#_last_log.close()
		if not _last_log:
			_last_rep_file = ''
		if debug > 0: 
			print "end", gMod+marker+NL,
		return _last_log
 

def printLog(cmd):
	cmd = regsub.gsub('@','@@',cmd)
#	cmd = regsub.gsub('\\"','\\\\"',cmd)
	print cmd
def printErrorLog(cmd, rc):
	print 'ERROR !!!'
	cmd = regsub.gsub('@','@@',cmd)
#	cmd = regsub.gsub('\\"','\\\\"',cmd)
	print 'Command:', cmd
	print 'Return Code:', rc
	print 'END OF ERROR MESSAGE'
# ---- VCS commands ----------------------------------

def CheckOut(debug=TEST):
	marker = "CheckOut"
	if debug > 0: 
		print "start", gMod+marker+NL,
	rc = 0

	# build common tc commmand options
	options = BuildCmdOptions(TRUE,TRUE,VERBOSE)
		
	cmd=gTeamc + " part -checkout " + options + ";"
	if debug > 1: print "cmd1: "
	printLog(cmd)
	rc = vcs.system(cmd)
	if rc != 0:
		printErrorLog(gMod+ marker+ " Error in cmd: "+cmd, rc)
		return vcs.test(rc)

	if debug > 0: 
		print "end", gMod+marker+NL,
	return vcs.test(rc)




def CheckOutProject():
		return TRUE


def getComponent(component, debug=TEST):
	marker = "getComponent"
	if debug > 0: 
		print "start", gMod+marker+NL
	title = "TeamConnection"
	model = PotGuiModel()
	model.SetValue("Component", component)
	# class textfield
	compField = PotTextField("Component")
	retval=ShowSubDialog("%s" % title,
		model,
		MakePageLayout(eVObjHExpand | eVObjVExpand,
			MakeSectionLayout(
				Form(
					items=[
						"Component:",compField,
					]	# items
				)	# Form
			),	# MakeSectionLayout
		)	# MakePageLayout
	)	# ShowSubDialog

	if retval:
		component = model.GetValue("Component")
		ret = (retval, component)
	else:
		ret = (retval, '')
	
		
	if debug > 1: print "gMod\t" + marker + "@BretValue: @b%d@x@B" % retval
	if debug > 0: 
		print "end", gMod+marker+NL,
	return ret
	
def getForce(debug=TEST):
	marker = "getForce"
	if debug > 0: 
		print "start", gMod+marker+NL
	title = "TeamConnection"
	force = 0
	model = PotGuiModel()
	model.SetValue("Force", force)
# in ver 3.0 PotGuiToggleButton verlangt nur 1 Parameter
#						"Force: ", PotGuiToggleButton("Force")
	retval=ShowSubDialog("%s" % title,
		model,
		MakePageLayout(eVObjHExpand | eVObjVExpand,
			MakeSectionLayout(
				Form(
					items=[
						"Force: ", PotGuiToggleButton("Force", "")
					]	# items
				)	# Form
			)	# MakeSectionLayout
		)	# MakePageLayout
	)	# ShowSubDialog

	# write settings to the file
	if retval:
		force = model.GetValue("Force")
	ret = (retval, force)
	if debug > 1: print ret			
	if debug > 1: print "gMod\t" + marker + "@BretValue: @b%d@x@B" % retval
	if debug > 0: 
		print "end", gMod+marker+NL,
	return ret
	
def getForceOrig(debug=TEST):
	marker = "getForce"
	if debug > 0: 
		print "start", gMod+marker+NL
	title = "TeamConnection"
	force = 0
	model = PotGuiModel()
	model.SetValue("Force", force)
	retval=ShowSubDialog("%s" % title,
		model,
		MakePageLayout(eVObjHExpand | eVObjVExpand,
			MakeSectionLayout(
				Form(
					items=[
						"Force: ", PotGuiToggleButton("Force")
					]	# items
				)	# Form
			)	# MakeSectionLayout
		)	# MakePageLayout
	)	# ShowSubDialog

	# write settings to the file
	if retval:
		force = model.GetValue("Force")
	ret = (retval, force)
	if debug > 1: print ret			
	if debug > 1: print "gMod\t" + marker + "@BretValue: @b%d@x@B" % retval
	if debug > 0: 
		print "end", gMod+marker+NL,
	return ret
	
def prepareCommentForTC(comment, debug=TEST):
	# if [ \"%C\" != \"*** empty log message ***\" ]; 
	if "*** empty log message ***" != comment:
		#when comment isn't empty add it
		remarks = string.strip(comment)
		if len(remarks) != 0:
			if debug > 1: print 'comment before preparation:', comment
			# translate back wrapping of '-sign
			comment = regsub.gsub('\'"\'"\'','\'',comment)
			# translate "-sign to \"-string 
			# r'\"' means it is raw string (backslash will not be replaced
			# and stays in string 
			comment = regsub.gsub('"',r'\"',comment)
			if debug > 1: print 'comment after preparation:', comment
			remarks = ' -remarks "' + comment + '"'
			if debug > 1: print 'remarks: ', remarks
		else:
			if debug > 1: print 'no empty log'
			remarks = ' -remarks "  "'
	else:
		if debug > 1: print 'empty log'
		remarks = ' -remarks "  "'
	
	return remarks

def CreateRepositoryFile(debug=TEST):
		marker = "CreateRepositoryFile"
		if debug > 0: 
			print "start", gMod+marker+NL
		
		options = BuildCmdOptions(TRUE,TRUE,VERBOSE)

#  per implizite einchecken in ein neues Work Area mit dem Namen von Sniff-ChangeSet.
#  wir finden es verwirrend. Work Area muss im Setting-Dialog implementiert werden.
		# if [ %S ];
#		if 0!=len(vcs.symbolName):
#		#if TRUE: # just for testing - replace with proper 'if' above
#		#if FALSE: # just for testing - replace with proper 'if' above
#			defect = vcs.getoutput("echo \"%s\" | sed -e 's/SNIFF_CHANGESET_//g'" %
#									vcs.symbolName)
#			defect = string.replace(vcs.symbolName, "SNIFF_CHANGESET_", "")
#			defect = string.strip(defect)
#			track = "-workarea " + defect
#		# fi;
#		if debug > 1:
#			print "track = ",
#			print track

		command = gTeamc + " part -create "
		command = command + options

		#get Component from developer
		#comp = "us#sniff"
		comp = ''
		ret = getComponent(comp)
		retval = ret[0]
		if not retval:
			printLog('#### CheckIn broken trough Component-Cancel ####')
			return FALSE 
		else:
			comp = ret[1]
			if debug > 1: print 'getComponent OK, comp: ', comp
		
		callstring= command + ' -component %s -text' % comp
		remarks = prepareCommentForTC(vcs.comment, debug)
		callstring = callstring + remarks
		cmd = callstring + ";"
		
		if debug > 1: print "cmd1: "	
		#write to the log
		printLog(cmd)
		#do it
		res = vcs.system(cmd)
		if res != 0:
			printErrorLog(gMod+ marker+ " Error in cmd: "+cmd, res)
			return vcs.test(res)

		if debug > 0: 
			print "end", gMod+marker+NL
		return vcs.test(res)


def CheckIn(debug=TEST):
		marker = "CheckIn"
		if debug > 0: 
			print "start", gMod+marker+NL
		rc = 0
		
		# if [ %S ];
		#msi
		#if 0!=len(vcs.symbolName):
		#if TRUE: # just for testing - replace with proper 'if' above
		#if FALSE: # just for testing - replace with proper 'if' above
		#	defect = vcs.getoutput("echo %s | sed -e 's/SNIFF_CHANGESET_//g'" %
		#							vcs.symbolName)
		#	track = "-workarea " + defect
		# fi;

		# build common tc commmand options
		options = BuildCmdOptions(TRUE,TRUE,VERBOSE)
		command = gTeamc + " part -checkin " + options
		remarks = prepareCommentForTC(vcs.comment, debug)
		callstring = command + remarks
		
		ret, force = getForce()
		if ret == 0:
			printLog('#### CheckIn broken trough Force-Cancel ####')
			return FALSE
			
		if force > 0:
			callstring = callstring + ' -force'

		callstring = callstring + ";"
		if debug > 1: print " teamc callstring  = "
		printLog(callstring)
		res = vcs.system(callstring)
		if debug > 1:
				print gTeamc + " callstring  returns: ",
				print res
		if debug > 0: 
			print "end", gMod+marker+NL
		return vcs.test(res)


def Lock(debug=TEST):
		marker = "Lock"
		if debug > 0: 
			print "start", gMod+marker+NL
		#settings = ('','','','','','')
		settings = ('','','','','')
		settings = readSettings()
		family = settings[0]
		user = settings[1]
		become = settings[2]
		rel = settings[3]
		area = settings[4]
		#relpath = settings[5]
		#cmd = gTeamc + " part -lock %s/%s -release %s -workarea %s;"
		#args = (vcs.projectDir, vcs.workingFile, rel, area)
		#cmd = cmd % args
		options = BuildCmdOptions(TRUE,FALSE,VERBOSE)
		cmd = gTeamc + " part -lock " + options + ";"
		if debug > 1: print "cmd1: "
		printLog(cmd)
		rc = vcs.system(cmd)
		if rc != 0:
			printErrorLog(gMod+ marker+ " Error in cmd: "+cmd, rc)
			return vcs.test(rc)
		if debug > 0: 
			print "end", gMod+marker+NL, 
		return TRUE


def SetWorkFileReadOnly():
		path = vcs.joinpath(vcs.workingDir,vcs.workingFile)
		chmod(path, 'ugo-w')
		return TRUE


def UpdateProject():
		print 'AdaptorTemplate: command UpdateProject not implemented'
		return TRUE


def UpdateFile():
		print 'AdaptorTemplate: command UpdateFile not implemented'
		return TRUE


def Unlock(debug=TEST):
		marker = "Unlock"
		if debug > 0: 
			print "start", gMod+marker+NL
		# build common tc commmand options
		options = BuildCmdOptions(TRUE,FALSE,VERBOSE)
		cmd = gTeamc + " part -unlock " + options + ";"
		if debug > 1: print "cmd1: "
		printLog(cmd)
		rc = vcs.system(cmd)
		if rc != 0:
			printErrorLog(gMod+ marker+ " Error in cmd: "+cmd, rc)
			return vcs.test(rc)
		if debug > 0: 
			print "end", gMod+marker+NL
		return TRUE

def BreakLock(debug=TEST):
		print 'Adaptor: command BreakLock not implemented'
		return TRUE


def DeleteVersion(debug=TEST):
	marker = "DeleteVersion"
	if debug > 0: 
		print "start", gMod+marker+NL,
	#cmd = gTeamc + " part -delete %s/%s -release %s -workarea %s ;"
	#args = (vcs.projectDir, vcs.workingFile, release, workarea)
	#cmd = cmd % args
	options = BuildCmdOptions(TRUE,FALSE,VERBOSE)
	cmd = gTeamc + " part -delete " + options + ";"
	if debug > 1: print "cmd1: "
	printLog(cmd)
	rc = vcs.system(cmd)
	if rc != 0:
		printErrorLog(gMod+ marker+ " Error in cmd: "+cmd, rc)
		return vcs.test(rc)
	if debug > 0: 
		print "end", gMod+marker+NL,
	return TRUE


def SetDescription():
		print 'AdaptorTemplate: command SetDescription not implemented'
		return TRUE


def SetSymbol():
		print 'AdaptorTemplate: command SetSymbol not implemented'
		return TRUE


def DeleteSymbol():
		print 'AdaptorTemplate: command DeleteSymbol not implemented'
		return TRUE


def ChangeComment():
		print 'AdaptorTemplate: command ChangeComment not implemented'
		return TRUE


def Description():
		print 'AdaptorTemplate: command Description not implemented'
		return TRUE


def History(debug=TEST):
	marker = "History"
	if debug > 0: 
		print "start", gMod+marker+NL
	log = log_with_history(FALSE)
	if not log:
		return FALSE
	vcs.output(log.history_str())
	if debug > 0: 
		print "end", gMod+marker+NL
	return TRUE
	
def Head(debug=TEST):
	marker=gMod+"Head: "
	if debug > 1: print marker
	log = log_with_history(TRUE)
	if not log:
		return FALSE
	return log.head_rev()
	

def SymbolList(debug=TEST):
	marker=gMod+"SymbolList: "
	if debug > 0: print marker
	log = log_with_history(FALSE)
	if not log:
		if debug > 0: 
			print "end", gMod+marker+NL
		return FALSE
	out_list = []
	while log:
		# giving lockers at SymbolList() only works with SNiFF+ 3.1
		#out_list.append('\014%s\t%s' % (log.work_file(), log.lockers()))
		out_list.append('\014%s' % (log.work_file()))
		out_list.append('HEAD: %s' % log.head_rev())
		symbols = log.symbolstr()
		if symbols:
			out_list.append(symbols)
		for rev in log.revision_list():
#			out_list.append(string.join((rev.rev, rev.date, rev.author, rev.lines)))
			out_list.append(string.join((rev.rev, rev.date,";", rev.author, ";", "+1 -1;")))
		log.next()
	vcs.output(string.join(out_list, NL)+NL)
	if debug > 0: 
		print "end", gMod+marker+NL
	return TRUE


def RevisionOfSymbol(debug=TEST):
	symbol = vcs.symbolName
	log = log_without_history(TRUE)
	if not log:
		return FALSE
	sym_defs = log.symbollist() 
	rev = ''
	for sym_def in sym_defs:
		[sym_name, version] = string.split(sym_def,':')
		if sym_name == symbol:
			rev = string.lstrip(version)
			break
	if rev:
		vcs.output(rev)
		return TRUE
	else:
		return FALSE


def HistoryOfRevision(debug=TEST):
	marker=gMod+"HistoryOfRevision: "
	if debug > 1: print marker
	log = log_with_history(TRUE)
	if not log:
		return FALSE
	rev = log.revision(vcs.revision)
	if not rev:
		return FALSE
	vcs.output(str(rev))
	return TRUE


def Comment():
		print 'AdaptorTemplate: command Comment not implemented'
		return TRUE


def Lockers(debug=TEST):
	#print 'AdaptorTemplate: command Lockers not implemented'
	#res = vcs.system(gTeamc + " report -raw  -view PartsOutView -where\
	#\"partNuPath = '%s/%s'\" | awk -F'|' '{print $5}'" % 
	#					(vcs.projectDir, vcs.workingFile))
	#return vcs.test(res)
	marker = "Lockers"
	if debug > 0: 
		print "start", gMod+marker+NL,
	log = log_with_history(FALSE)
	out_list = []
	processed = {}
	if debug > 1: print 'log:', log
	while log:
		if debug > 1: print marker, 'in while'
		processed[log.work_file()] = None
		out_list.append('%s %s' % (log.work_file(), log.lockers()))
		log.next()
	wfiles = string.split(vcs.workingFile)
	for wfile in wfiles:
		if not processed.has_key(wfile):
			out_list.append(wfile)
	vcs.output(string.join(out_list, NL))
	if debug > 0: 
		print 'out_list:', out_list, NL
		print "end", gMod+marker+NL,
	return TRUE
	


def IsLockedBy(debug=TEST):
		marker = "IsLockedBy"
		if debug > 0: 
			print "start", gMod+marker+NL
		if SYSTEM==UNIX:
			res = vcs.system(gTeamc + " report -raw  -view PartsOutView -where\
		\"partNuPath = '%s/%s'\" | awk -F'|' '{print $5}'" % 
							(vcs.projectDir, vcs.workingFile))
		else:
			res = vcs.system(gTeamc + " report -raw  -view PartsOutView -where\
		\"partNuPath = '\\\%s/%s\\\'\" | awk -F'|' '{print $5}'" % 
							(vcs.projectDir, vcs.workingFile))
		if debug > 0: 
			print "end", gMod+marker+NL
		return vcs.test(res)

def IsLocked(debug=TEST):
		marker = "IsLocked"
		if debug > 0: 
			print "start", gMod+marker+NL
		if SYSTEM==UNIX:
			user = vcs.getoutput(gTeamc + " report -raw  -view PartsOutView -where\
			\"partNuPath = '%s/%s'\" | awk -F'|' '{print $5}'" % 
								(vcs.projectDir, vcs.workingFile))
		else:
			user = vcs.getoutput(gTeamc + " report -raw  -view PartsOutView -where\
			\"partNuPath = \\\'%s/%s\\\'\" | awk -F'|' '{print $5}'" % 
								(vcs.projectDir, vcs.workingFile))
		if debug > 0: 
			print "end", gMod+marker+NL
		return 0!=len(user)


def IsDifferent(debug=TEST):
		marker = "IsDifferent"
		if debug > 0: 
			print "start", gMod+marker+NL,
		options = BuildCmdOptions(TRUE,TRUE,VERBOSE)
		# init vstr
		vstr = ""
		# if [ %V ];
		if 0!=len(vcs.revision):
			vstr = "-version " + vcs.revision
		# fi;
		# if [ %v ] ;
		if 0!=len(vcs.revision2):
			vstr = "-version " + vcs.revision2
		# fi;
		# if [ -f %T ] ;
		if os.path.isfile(vcs.tmpFile):
			vcs.rm_f(vcs.tmpFile)
		# fi;
		command=gTeamc + " part -extract " 
		command = command + options
		command = command + " -stdout %s > %s;"
		# NB bug in supplied shell script; $version used instead of $vstr
		args=(vstr, vcs.tmpFile)
		callstring = command % args
		if debug > 1:
			print gTeamc + " callstring 1 = ",
			print callstring
		res = vcs.system(callstring)
		if debug > 1:
			print gTeamc + " callstring 1 returns: ",
			print res
		res = vcs.system("diff %s %s/%s > /dev/null 2>&1;" % 
							(vcs.tmpFile, vcs.projectDir, vcs.workingFile))
		if debug > 0: 
			print "end", gMod+marker+NL,
		return vcs.test(res)


def DiffText_W_V_Orig(debug=TEST):
		marker = "DiffText_W_V"
		if debug > 0: 
			print "start", gMod+marker+NL,
		rel = vcs.getoutput('cat $HOME/.SNiFF_teamc_working_release')
		area = vcs.getoutput('cat $HOME/.SNiFF_teamc_WorkArea')
		rel = string.strip(rel)
		area = string.strip(area)
		tmpf="%s/File2" % (vcs.tmpDir)
		if os.path.isfile(tmpf):
			vcs.rm_f(tmpf)
		# if [ \"%v\" ] ;
		if 0!=len(vcs.revision2):
			vstr = "-version " + vcs.revision2
		else:
			vstr = ""
		# fi ;
		command=gTeamc + " part -extract %s/%s -relative %s -release %s -workarea\
		%s -stdout %s > %s;"
		args=(vcs.projectDir, vcs.workingFile, vcs.privateRoot, rel, area, vstr,
				tmpf)
		callstring = command % args
		if debug > 1:
			print gTeamc + " callstring 1 = ",
			print callstring
		res = vcs.system(callstring)
		if debug > 1:
			print gTeamc + " callstring 1 returns: ",
			print res
		out = vcs.getoutput("diff %s/%s/%s %s" % 
							(vcs.privateRoot, vcs.projectDir, vcs.workingFile, 
								tmpf))
		vcs.output(out)
		if debug > 0: 
			print "end", gMod+marker+NL, 
		return out == ''


#show differences between version and working file
def DiffText_W_V(debug=TEST):
	marker = "DiffText_W_V"
	if debug > 0: 
		print "start", gMod+marker+NL,
	rc = 0
	tmpf="%s/File2" % (vcs.tmpDir)
	if os.path.isfile(tmpf):
		vcs.rm_f(tmpf)
	# if [ \"%v\" ] ;
	if 0!=len(vcs.revision2):
		vstr = "-version " + vcs.revision2
	else:
		vstr = ""
	# fi ;

	options = BuildCmdOptions(TRUE,TRUE,VERBOSE)
	cmd = gTeamc + " part -extract " 
	if debug > 1: print marker, "cmd = ", cmd
	if debug > 1: print marker, "options = ", options
	cmd = cmd + options
	cmd = cmd + " -stdout %s > %s;" % (vstr, tmpf)
	if debug > 1: print "cmd1: "
	printLog(cmd)
	rc = vcs.system(cmd)
	if rc != 0:
		printErrorLog(gMod+ marker+ " Error in cmd: "+cmd, rc)
		return vcs.test(rc)

	out = vcs.getoutput("diff %s/%s/%s %s" % 
						(vcs.privateRoot, vcs.projectDir, vcs.workingFile, 
							tmpf))
	vcs.output(out)
	if debug > 0: 
		print "end", gMod+marker+NL, 
	return out == ''


#show differences between two versions
def DiffText_V_V(debug=TEST):
	marker = "DiffText_V_V"
	if debug > 0: 
		print "start", gMod+marker+NL,
	command = gTeamc + " part -extract " 
	options = BuildCmdOptions(TRUE,TRUE,VERBOSE)
	tmpf1="%s_%s" % (vcs.tmpFile, vcs.revision)
	tmpf2="%s/File2" % (vcs.tmpDir)
	if os.path.isfile(tmpf2):
		vcs.rm_f(tmpf2)
	# if [ \"%V\" ] ;
	if 0!=len(vcs.revision):
		vstr = "-version " + vcs.revision
	else:
		vstr = ""
	# fi ;
	cmd = command + options
	if debug > 1: print marker, "cmd1:", cmd
	cmd = cmd + " -stdout %s > /dev/null 2>&1;" % vstr
	if debug > 1: print "cmd2: "
	printLog(cmd)
	rc = vcs.system(cmd)
	if rc != 0:
		Err = 'Version %s of file %s/%s/%s not found!' % (vcs.revision, vcs.privateRoot, vcs.projectDir, vcs.workingFile)
		printErrorLog(gMod + marker + Err, rc)
		return vcs.test(rc)

	# if [ \"%v\" ] ;
	if 0!=len(vcs.revision2):
		vstr = "-version " + vcs.revision2
	else:
		vstr = ""
	# fi ;
	cmd = command + options
	if debug > 1: print marker, "cmd3:", cmd
	cmd = cmd + " -stdout %s > /dev/null 2>&1;" % vstr
	if debug > 1: print "cmd4: "
	printLog(cmd)
	rc = vcs.system(cmd)
	if rc != 0:
		Err = 'Version %s of file %s/%s/%s not found!' % (vcs.revision2, vcs.privateRoot, vcs.projectDir, vcs.workingFile)
		printErrorLog(gMod + marker + Err, rc)
		return vcs.test(rc)
	else:
		cmd = command + options
		if debug > 1: print marker, "cmd5:", cmd
		cmd = cmd + " -stdout %s > %s" % (vstr, tmpf2)
		if debug > 1: print "cmd6: "
		printLog(cmd)
		rc = vcs.system(cmd)
		if rc != 0:
			printErrorLog(gMod+ marker+ " Error in cmd: "+cmd, rc)
			return vcs.test(rc)
			
	# fi;

	out = vcs.getoutput("diff %s %s" % (tmpf1, tmpf2))
	vcs.output(out)
	if debug > 0: 
		print "end", gMod+marker+NL, 
	return out == ''

def DiffText_V_V_Orig(debug=TEST):
		marker = "DiffText_V_V"
		if debug > 0: 
			print "start", gMod+marker+NL,
		rel = vcs.getoutput('cat $HOME/.SNiFF_teamc_working_release')
		area = vcs.getoutput('cat $HOME/.SNiFF_teamc_WorkArea')
		rel = string.strip(rel)
		area = string.strip(area)
		if debug > 1:
			print "rel = ",
			print rel
			print "area = ",
			print area
		tmpf1="%s_%s" % (vcs.tmpFile, vcs.revision)
		tmpf2="%s/File2" % (vcs.tmpDir)
		if os.path.isfile(tmpf2):
			vcs.rm_f(tmpf2)
		# if [ \"%V\" ] ;
		if 0!=len(vcs.revision):
			vstr = "-version " + vcs.revision
		else:
			vstr = ""
		# fi ;
		command=gTeamc + " part -extract  %s/%s -release %s -workarea %s -relative\
		%s -stdout  %s > /dev/null 2>&1;"
		# NB bug in supplied shell script in that $area is used but not set
		args=(vcs.projectDir, vcs.workingFile, rel, area, vcs.privateRoot, vstr)
		callstring = command % args
		if debug > 1:
			print gTeamc + " callstring 1 = ",
			print callstring
		res = vcs.system(callstring)
		if debug > 1:
			print gTeamc + " callstring 1 returns: ",
			print res
		# if [ $res != 0 ] ;
		if 0!=res:
		#if TRUE: # just for testing - replace with proper 'if' above
			command="echo \"Error: Version %s of file %s/%s/%s not found!\" \
			1>&2;"
			args=(vcs.revision, vcs.privateRoot, vcs.projectDir,vcs.workingFile)
			callstring = command % args
			vcs.system(callstring)
			return FALSE
		# fi;
		# if [ \"%v\" ] ;
		if 0!=len(vcs.revision2):
			vstr = "-version " + vcs.revision2
		else:
			vstr = ""
		# fi ;
		command=gTeamc + " part -extract  %s/%s -release %s -workarea %s -relative\
		%s -stdout  %s > /dev/null 2>&1;"
		# NB bug in supplied shell script in that $area is used but not set
		args=(vcs.projectDir, vcs.workingFile, rel, area, vcs.privateRoot, vstr)
		callstring = command % args
		if debug > 1:
			print gTeamc + " callstring 2 = ",
			print callstring
		res = vcs.system(callstring)
		if debug > 1:
			print gTeamc + " callstring 2 returns: ",
			print res
		# if [ $res != 0 ] ;
		if 0!=res:
		#if TRUE: # just for testing - replace with proper 'if' above
			command="echo \"Error: Version %s of file %s/%s/%s not found!\" \
			1>&2;"
			args=(vcs.revision2, vcs.privateRoot,vcs.projectDir,vcs.workingFile)
			callstring = command % args
			vcs.system(callstring)
			return FALSE
		else:
			command=gTeamc + " part -extract  %s/%s -release %s -workarea %s \
			-relative %s -stdout %s > %s"
			args=(vcs.projectDir, vcs.workingFile, rel, area, vcs.privateRoot, 
					vstr, tmpf2)
			callstring = command % args
			if debug > 1:
				print gTeamc + " callstring 3 = ",
				print callstring
			res = vcs.system(callstring)
			if debug > 1:
				print gTeamc + " callstring 3 returns: ",
				print res
		# fi;
		out = vcs.getoutput("diff %s %s" % (tmpf1, tmpf2))
		vcs.output(out)
		if debug > 0: 
			print "end", gMod+marker+NL, 
		return out == ''


def RepositoryDir(debug=TEST):
		#res = "%s/%s" % (vcs.RCCSPath, vcs.catDir)
		res = vcs.joinpath(vcs.RCCSPath, vcs.catDir, 'SCCS')
		if debug > 1:
			print "res = ",
			print res
		vcs.output(res)
		return TRUE

def RepositoryFile(debug=TEST):
		#res = "%s/s.%s" % (vcs.repositoryDir, vcs.workingFile)
		res = vcs.joinpath(vcs.repositoryDir, vcs.workingFile)
		if debug > 1:
			print "res = ",
			print res
		vcs.output(res)
		return TRUE

def TempDir(debug=TEST):
		res = "/tmp/.sniffdir2/teamc_%s%s" % (vcs.user, vcs.pid)
		if debug > 1:
			print "res = ",
			print res
		vcs.output(res)
		return TRUE

def TempFile(debug=TEST):
		res = "%s/%s" % (vcs.tmpDir, vcs.workingFile)
		if debug > 1:
			print "res = ",
			print res
		vcs.output(res)
		return TRUE

def BranchDef():
		vcs.output('I')
		return TRUE

def RepositoryCheckDef():
	#vcs.output('I')
	vcs.output('C')
	return TRUE

def CheckRepositoryDir():
		return TRUE


def CheckRepositoryFile(debug=TEST):
		#if TF_TEST: return FALSE
		marker = "CheckRepositoryFile"
		if debug > 0: 
			print "start", gMod+marker+NL,
		rc = 0

		options = BuildCmdOptions(FALSE,FALSE,VERBOSE)		

		if SYSTEM==UNIX:
			command = gTeamc + " report -raw -view PartView -where \"nuPathName = ('%s/%s')\" "
		else:
			command = gTeamc + " report -raw -view PartView -where \"nuPathName = (\\\'%s/%s\\\')\" "	
		args = (vcs.projectDir,vcs.workingFile)
		callstring = command % args
		callstring = callstring + options + ";"
		if debug > 1:
			print " teamc callstring 1 = ",
			print callstring
		printLog(callstring)
		res = vcs.getoutput(callstring)
		res = string.strip(res)
		if debug > 1:
			print gTeamc + " callstring 1 returns: ",
			print res
		#
		#when file not found and -verbose switch is on TC responds 
		#with "0 records selected, so we compare 
		#simply the first character to "0"
		if VERBOSE:
			retval = res != "0 records selected"
		else:
			retval = 0!=len(res)

		if debug > 0: 
			print "end", gMod+marker+NL,
		return retval

def DateOfRepositoryFile(debug=TEST):
	marker = "DateOfRepositoryFile"
	if debug > 0: 
		print "start", gMod+marker+NL,
	mtime = time.time()	# remote repositories are never the same
	vcs.output(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(mtime)))
	if debug > 0: 
		print "end", gMod+marker+NL,
	return TRUE


def CreateRepositoryDir():
		rc = vcs.mkdir_p(vcs.repositoryDir, 0775)
		return vcs.test(rc)

def TestTool():
		return vcs.is_reachable("teamc")

def Constructor():
	if not os.path.isdir(vcs.tmpDir):
		vcs.mkdir_p(vcs.tmpDir)
	return TRUE


def Destructor():
		if os.path.isdir(vcs.tmpDir):
				vcs.rm_fr(vcs.tmpDir)
		return TRUE


#show TeamConnection parameter Dialog window
def settings(debug=TEST):
	marker = "settings"
	if debug > 0: 
		print "start", gMod+marker+NL
	#settings = ('','','','','','')
	settings = ('','','','','')
	settings = readSettings()
	if debug > 1: print 'settings: ', settings
	family = settings[0]
	user = settings[1]
	become = settings[2]
	release = settings[3]
	workarea = settings[4]
	#relpath = settings[5]
	title = "TeamConnection Settings"
	model = PotGuiModel()
	model.SetValue("Family", family)
	model.SetValue("User", user)
	model.SetValue("Become", become)
	model.SetValue("Release", release)
	model.SetValue("WorkArea", workarea)
	#model.SetValue("RelativePath", relpath)
	# class textfield
	familyField = PotTextField("Family")
	userField = PotTextField("User")
	becomeField = PotTextField("Become")
	releaseField = PotTextField("Release")
	workareaField = PotTextField("WorkArea")
	#relPathField = PotTextField("RelativePath")
	#msi
	#itemsList=EnvGetIndices("VCS_INTERFACE")
	#for v in itemsList:
	#	popup.AddItem(v,v)
	retval=ShowSubDialog("%s" % title,
		model,
		MakePageLayout(eVObjHExpand | eVObjVExpand,
			MakeSectionLayout(
				Form(
					items=[
						"Family:",familyField,
						"User:",userField,
						"Become:", becomeField,
						"Release:", releaseField,
						"Work area:", workareaField,
					]	# items
				)	# Form
			),	# MakeSectionLayout
		)	# MakePageLayout
	)	# ShowSubDialog
#						"Relative path:", relPathField

	# write settings to the file
	if retval:
		family = model.GetValue("Family")
		user = model.GetValue("User")
		become = model.GetValue("Become")
		release = model.GetValue("Release")
		workarea = model.GetValue("WorkArea")
		#relpath = model.GetValue("RelativePath")
		#if debug > 1: print 'relpath in settings:', relpath
		#writeSettings(family, user, become, release, workarea, relpath)
		writeSettings(family, user, become, release, workarea)
		
	if debug > 1: print "gMod\t" + marker + "@BretValue: @b%d@x@B" % retval

	if debug > 0: 
		print "end", gMod+marker+NL,
	return retval
#settings


if __name__ == "__main__":
	import TCReload
	TCReload.ReloadAll()
	pass
